import axios from 'axios';

const API_BASE_URL = process.env.REACT_APP_API_BASE_URL || 'http://localhost:3001/api';

const api = axios.create({
  baseURL: API_BASE_URL,
  timeout: 10000,
});

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
api.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    if (error.response && error.response.status === 401) {
      // token过期或无效，清除本地存储并跳转到登录页
      localStorage.removeItem('token');
      localStorage.removeItem('user');
      if (window.location.pathname !== '/login') {
        window.location.href = '/login';
      }
    }
    return Promise.reject(error);
  }
);

// 用户相关API
export const register = (userData) => api.post('/register', userData);
export const login = (credentials) => api.post('/login', credentials);

// 函数相关API
export const createFunction = (functionData) => api.post('/functions', functionData);
export const getFunctions = (searchKeyword, publishedOnly = false) => {
  const params = {};
  if (searchKeyword) {
    params.search = searchKeyword;
  }
  if (publishedOnly) {
    params.published = 'true';
  }
  return api.get('/functions', { params });
};
export const getFunction = (id) => api.get(`/functions/${id}`);
export const updateFunction = (id, functionData) => api.put(`/functions/${id}`, functionData);
export const deleteFunction = (id) => api.delete(`/functions/${id}`);
export const deployFunction = (id) => api.post(`/functions/${id}/deploy`);
export const publishFunction = (id, published) => api.patch(`/functions/${id}/publish`, { published });

// 实例相关API
export const getInstances = () => api.get('/instances');
export const getInstance = (id) => api.get(`/instances/${id}`);
export const startInstance = (id) => api.post(`/instances/${id}/start`);
export const stopInstance = (id) => api.post(`/instances/${id}/stop`);

export default api;